//
//  ViewController.m
//  Homework3
//
//  Created by 王佩 on 15/9/25.
//  Copyright (c) 2015年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    NSString * documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
    
    NSString * filePath = [documentsPath stringByAppendingPathComponent:@"timeRecord.txt"];
    
    
    NSFileManager * fileManager = [NSFileManager defaultManager];
    
    BOOL success = [fileManager createFileAtPath:filePath contents:nil attributes:nil];
    
    
    NSLog(@"%@",filePath);
    if (success) {
        NSLog(@"create file success!");
    }
    
    NSFileHandle * fileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];
    
    
    
    [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timing:) userInfo:@[fileHandle,filePath] repeats:YES];


}

- (void)timing:(NSTimer *)timer
{
    static int count = 0;
    
    NSFileHandle * fileHandle = [((NSArray *)timer.userInfo) objectAtIndex:0];
    
    
    // 当前时间.
    NSDate * nowDate = [NSDate date];
    
    NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
    
    [formatter setDateFormat:@"yyyy/MM/dd HH:mm:ss"];
    NSString * dateString = [formatter stringFromDate:nowDate];
    dateString = [dateString stringByAppendingString:@"\n"];
//    NSDictionary * dic = @{@"date":dateString};
//    NSString * filePath = [((NSArray *)timer.userInfo) objectAtIndex:1];
//    [dic writeToFile:filePath atomically:YES];
//    NSData * data = [NSData dataWithContentsOfFile:filePath];
    
    NSData * data = [dateString dataUsingEncoding:NSUTF8StringEncoding];
    
    [fileHandle writeData:data];
    
    count++;
    if (count == 60) {
        [fileHandle closeFile];
        [timer invalidate];
    }
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
